package com.rfid.a252robot.activity.presenter;

import android.os.Handler;
import android.text.TextUtils;

import com.rfid.a252robot.activity.view.IBookInfoView;
import com.rfid.a252robot.base.BasePresenter;
import com.rfid.a252robot.event.BoxOpenEvent;
import com.rfid.a252robot.event.QrEvent;
import com.rfid.a252robot.net.BookLibApi;
import com.rfid.a252robot.net.bean.BookInfoRespon1;
import com.rfid.a252robot.task.BorrowRestoreTask;
import com.rfid.acs.net.bean.ReaderInfoBean;
import com.rfid.common.log.LogUtils;
import com.rfid.db.bean.Book;
import com.rfid.manager.BookManager;
import com.rfid.manager.DBManager;
import com.rfid.manager.TaskManager;
import com.rfid.mqtt.MqttManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import io.reactivex.functions.Consumer;

public class BookInfoPresenter extends BasePresenter<IBookInfoView> {

    boolean isStop;
    Executor mExecutor = Executors.newSingleThreadExecutor();
    Handler handler = new Handler();
    public Book getBook(String barcode) {
        return DBManager.getBook(barcode);
    }


    public void startScanQr() {
        isStop = false;
//        mView.onLoginSuccess("2");
        EventBus.getDefault().register(this);
        MqttManager.INSTANCE.scanQr();
//        onQrCode(new QrEvent("2"));
    }

    public void stopScanQr(){
        EventBus.getDefault().unregister(this);
        isStop = true;
    }

    public void getBookInfo(String isbn) {
        if (TextUtils.isEmpty(isbn)) {
            return;
        }
        mExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    BookInfoRespon1 respon1 = BookLibApi.INSTANCE.getBookInfo1(isbn);
                    String message = respon1.getResult().getSummary();
                    String amsg = respon1.getResult().getAuthorIntroduction();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (mView != null) {
                                mView.onIntroInfo(message,amsg);
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQrCode(QrEvent event) {
        String reader = event.getQrCode();
        if (mView != null && event.isSuccess()) {
            mView.onScanResult(reader);
        }
    }

    public void login(String readerId, String pwd, int boxNum) {
        BookManager.INSTANCE.searchReaderInfo(readerId,pwd)
                .subscribe(new Consumer<ReaderInfoBean>() {
                    @Override
                    public void accept(ReaderInfoBean readerInfoBean) throws Exception {
                        if (mView != null) {
                            if (readerInfoBean.isSuccess()) {
                                try {
                                    int max = Integer.valueOf(readerInfoBean.getBookLimit());
                                    int current = Integer.valueOf(readerInfoBean.getBookCount());
                                    int bc = DBManager.getBooks(boxNum).size();
                                    if (current + bc > max) {
                                        mView.onLoginFail("所开箱门内书籍数量超出用户可借书籍数量，请重新选择");
                                        return;
                                    }
                                } catch (Exception e) {
                                }
                                mView.onLoginSuccess(readerInfoBean.getReaderNo(),pwd);
                            } else {
                                mView.onLoginFail(readerInfoBean.getHintMessage());
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        LogUtils.e(throwable);
                        if (mView != null) {
                            mView.onLoginFail(throwable.getMessage());
                        }
//                        qrNotMatch();
                    }
                });
    }

    private void qrNotMatch() {
        if (!isStop) {
            MqttManager.INSTANCE.scanQr();
        }
    }

}
